package entities.concept;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import option.KBVocabulary;

import utils.Display;

//import entities.role.Role;

/**
 * And concepts: a set of concepts in conjunction
 * 
 * @author j55wu
 * 
 */
public class AndConcept extends NaryConcept {

	// TODO: hack to preserve order in toString()
	private Concept c1;
	private Concept c2;

	public AndConcept(Set<Concept> in) {
		super(in);
	}

	public AndConcept(Concept c1, Concept c2) {
		this.cons.add(c1);
		this.cons.add(c2);
		this.c1 = c1;
		this.c2 = c2;
	}

	public AndConcept(List<Concept> cs) {
		this.cons.addAll(cs);
	}

	private volatile int hashCode = 0;

	@Override
	public int hashCode() {
		if (hashCode != 0) {
			return hashCode;
		}
		final int prime = 31;
		// int result = 1 + KBVocabulary.AND.hashCode();
		int result = 17;
		for (Concept c : cons) {
			result = prime * result + ((c == null) ? 0 : c.hashCode());
		}
		// result = prime * result + cons.hashCode();
		hashCode = result;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!(obj instanceof AndConcept))
			return false;
		AndConcept that = (AndConcept) obj;
		if (cons == null) {
			if (that.cons != null)
				return false;
		} else if (!cons.equals(that.cons))
			return false;
		return true;
	}

	@Override
	public String toString() {
		if (c1 != null && c2 != null && cons.size() <= 2) {
			return "[" + c1.toString() + " " + Display.ANDUNICODE + " "
					+ c2.toString() + "]";
		}
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		Iterator<Concept> iter = cons.iterator();
		while (iter.hasNext()) {
			Concept n = iter.next();
			if (n == null) {
				System.err.println("WARNING: Null entry in AND concept");
				continue;
			}
			sb.append(n.toString());
			if (iter.hasNext()) {
				sb.append(" " + Display.ANDUNICODE + " ");
			}
		}
		sb.append("]");
		return sb.toString();
	}

	public String toSerializedString() {
		if (c1 != null && c2 != null && cons.size() <= 2) {
			return " (" + KBVocabulary.AND + " " + c1.toSerializedString()
					+ " " + c2.toSerializedString() + ") ";
		}
		StringBuilder sb = new StringBuilder();
		sb.append(" (" + KBVocabulary.AND + " ");
		for (Concept c : cons) {
			sb.append(c.toSerializedString() + " ");
		}
		sb.append(") ");
		return sb.toString();
	}
	

}
